package com.wyzz.hr.bo.impl;

import java.util.*;
import org.apache.axis.utils.StringUtils;
import org.hibernate.criterion.*;
import org.springframework.util.ObjectUtils;

import com.wyzz.hr.base.BaseAction;
import com.wyzz.hr.bo.IDepartmentBO;
import com.wyzz.hr.bo.IPerfplanBO;
import com.wyzz.hr.dao.IPerfplanDAO;
import com.wyzz.hr.pojo.Employee;
import com.wyzz.hr.pojo.Empsalarypay;
import com.wyzz.hr.pojo.Perfplan;
import com.wyzz.hr.pojo.Perfplanperiod;
import com.wyzz.hr.pojo.Perfplanscore;
import com.wyzz.hr.pojo.Perfschema;
import com.wyzz.hr.pojo.PositionBase;
import com.wyzz.hr.util.BaseCrit;
import com.wyzz.hr.util.Pager;

public class PerfplanBOImpl implements IPerfplanBO {

	public PerfplanBOImpl() {
	}

	public IPerfplanDAO getPerfplanDAO() {
		return perfplanDAO;
	}

	public void setPerfplanDAO(IPerfplanDAO perfplanDAO) {
		this.perfplanDAO = perfplanDAO;
	}

	public List searchPerfplan(DetachedCriteria dc, Pager page) {
		BaseAction.addOrders(dc, page, new String[] { (new StringBuilder())
				.append(Perfplan.PROP_PP_NO).append("-down").toString() });
		page.splitPage(dc);
		return perfplanDAO.findByCriteria(dc, page.getPageSize(), page
				.getCurrentPage());
	}

	public void saveOrUpdateList(List perfplanList) {
		if (perfplanList == null || perfplanList.size() == 0) {
			return;
		} else {
			perfplanDAO.saveOrupdate(perfplanList);
			return;
		}
	}

	public Perfplan loadPerfplanById(String id) {
		if (StringUtils.isEmpty(id))
			return null;
		DetachedCriteria dc = DetachedCriteria.forClass(Perfplan.class);
		dc.createAlias(Perfplan.PROP_PP_PS_ID, "ppPsId", 1);
		dc.createAlias(Perfplan.PROP_PP_PPP_ID, "ppPppId", 1);
		dc.createAlias(Perfplan.PROP_PP_EMP_ID, "ppEmpId", 1);
		dc.createAlias((new StringBuilder()).append(Perfplan.PROP_PP_EMP_ID)
				.append(".").append(Employee.PROP_EMP_PB_NO).toString(),
				"empPbNo", 1);
		dc.createAlias((new StringBuilder()).append(Perfplan.PROP_PP_EMP_ID)
				.append(".").append(Employee.PROP_EMP_PB_NO).append(".")
				.append(PositionBase.PROP_PB_SUP_ID).toString(), "pbSupId", 1);
		dc.createAlias(Perfplan.PROP_PP_DEPT_ID, "ppDeptId", 1);
		dc.createAlias(Perfplan.PROP_PP_PB_ID, "ppPbId", 1);
		BaseCrit.addDC(dc, Perfplan.PROP_PP_ID, "eq", new String[] { id });
		List tempPlan = perfplanDAO.findByCriteria(dc);
		if (tempPlan.size() >= 1)
			return (Perfplan) tempPlan.get(0);
		else
			return null;
	}

	public void saveOrUpdate(Perfplan plan) {
		perfplanDAO.saveOrupdate(plan);
	}

	public Perfplan loadPerfplan(String id, String fetch[]) {
		return (Perfplan) perfplanDAO.loadObject(Perfplan.class, id, fetch,
				new boolean[0]);
	}

	public void updatePerfplan(Perfplan perfplan) {
		perfplanDAO.saveOrupdate(perfplan);
	}

	public void deletePerfplan(String ppId[]) {
		String hql = "select ppe.ppeId from Perfplanemp ppe where ppe.ppePpId.ppId in (";
		String ppeHql = "delete from Perfplanemp ppe where ppe.ppePpId.ppId in (";
		String ppsHql = "delete from Perfplanscore pps where pps.ppsPpId.ppId in (";
		String ppHql = "delete from Perfplan pp where pp.ppId in (";
		for (int i = 0; i < ppId.length; i++) {
			hql = (new StringBuilder()).append(hql).append("'").append(ppId[i])
					.append("'").toString();
			ppeHql = (new StringBuilder()).append(ppeHql).append("'").append(
					ppId[i]).append("'").toString();
			ppsHql = (new StringBuilder()).append(ppsHql).append("'").append(
					ppId[i]).append("'").toString();
			ppHql = (new StringBuilder()).append(ppHql).append("'").append(
					ppId[i]).append("'").toString();
			if (i < ppId.length - 1) {
				hql = (new StringBuilder()).append(hql).append(",").toString();
				ppeHql = (new StringBuilder()).append(ppeHql).append(",")
						.toString();
				ppsHql = (new StringBuilder()).append(ppsHql).append(",")
						.toString();
				ppHql = (new StringBuilder()).append(ppHql).append(",")
						.toString();
			}
		}

		hql = (new StringBuilder()).append(hql).append(")").toString();
		ppeHql = (new StringBuilder()).append(ppeHql).append(")").toString();
		ppsHql = (new StringBuilder()).append(ppsHql).append(")").toString();
		ppHql = (new StringBuilder()).append(ppHql).append(")").toString();
		List perfplanempIdList = perfplanDAO.exeHqlList(hql);
		if (!perfplanempIdList.isEmpty()) {
			hql = "delete from Perfplanempscore ppes where ppes.ppesPpeId.ppeId in (";
			for (int i = 0; i < perfplanempIdList.size(); i++) {
				hql = (new StringBuilder()).append(hql).append("'").append(
						perfplanempIdList.get(i).toString()).append("'")
						.toString();
				if (i != 0 && i != perfplanempIdList.size() - 1)
					hql = (new StringBuilder()).append(hql).append(",")
							.toString();
			}

			hql = (new StringBuilder()).append(hql).append(")").toString();
			perfplanDAO.exeHql(hql);
		}
		perfplanDAO.exeHql(ppeHql);
		perfplanDAO.exeHql(ppsHql);
		perfplanDAO.exeHql(ppHql);
	}

	public List searchByPlanIds(String ids[]) {
		DetachedCriteria dc = DetachedCriteria.forClass(Perfplan.class);
		dc.createAlias(Perfplan.PROP_PP_PS_ID, "ppPsId", 1);
		dc.createAlias(Perfplan.PROP_PP_PPP_ID, "ppPppId", 1);
		dc.createAlias(Perfplan.PROP_PP_EMP_ID, "ppEmpId", 1);
		dc.createAlias((new StringBuilder()).append(Perfplan.PROP_PP_EMP_ID)
				.append(".").append(Employee.PROP_EMP_PB_NO).toString(),
				"empPbNo", 1);
		dc.createAlias((new StringBuilder()).append(Perfplan.PROP_PP_EMP_ID)
				.append(".").append(Employee.PROP_EMP_PB_NO).append(".")
				.append(PositionBase.PROP_PB_SUP_ID).toString(), "pbSupId", 1);
		dc.createAlias(Perfplan.PROP_PP_DEPT_ID, "ppDeptId", 1);
		dc.createAlias(Perfplan.PROP_PP_PB_ID, "ppPbId", 1);
		org.hibernate.criterion.Criterion tempc = Restrictions.in(
				Perfplan.PROP_PP_ID, ids);
		dc.add(tempc);
		return perfplanDAO.findByCriteria(dc);
	}

	public boolean addPerfplan(List perfplanList, List perfplanempList,
			List perfplanscoreList) {
		try {
			int maxNo = getMaxNo();
			for (Iterator i$ = perfplanList.iterator(); i$.hasNext();) {
				Perfplan perfplan = (Perfplan) i$.next();
				perfplan.setPpNo(Integer.valueOf(maxNo));
				maxNo++;
			}

			if (perfplanList != null && perfplanList.size() > 0)
				perfplanDAO.saveOrupdate(perfplanList);
			if (perfplanempList != null && perfplanempList.size() > 0)
				perfplanDAO.saveOrupdate(perfplanempList);
			if (perfplanscoreList != null && perfplanscoreList.size() > 0)
				perfplanDAO.saveOrupdate(perfplanscoreList);
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}

	public int getMaxNo() {
		List result = perfplanDAO.exeHqlList("select max(ppNo) from Perfplan");
		if (result.isEmpty() || result.get(0) == null)
			return 1;
		else
			return 1 + ((Integer) (Integer) result.get(0)).intValue();
	}

	public List getPerfplanIds(String pppId, String empIds[]) {
		if (empIds == null)
			return null;
		String hql = "select pp.ppEmpId.id from Perfplan pp where pp.ppEmpId.id in (";
		for (int i = 0; i < empIds.length; i++) {
			hql = (new StringBuilder()).append(hql).append("'").append(
					empIds[i]).append("'").toString();
			if (i != empIds.length - 1)
				hql = (new StringBuilder()).append(hql).append(",").toString();
		}

		hql = (new StringBuilder()).append(hql).append(
				") and pp.ppPppId.pppId = '").append(pppId).append("'")
				.toString();
		List list = perfplanDAO.exeHqlList(hql);
		if (list.isEmpty())
			return null;
		List result = new ArrayList();
		for (int i = 0; i < list.size(); i++)
			result.add(list.get(i).toString());

		return result;
	}

	public void updateStatus(Integer status, String ppId[]) {
		if (ppId == null || ppId.length == 0)
			return;
		String arr$[] = ppId;
		int len$ = arr$.length;
		for (int i$ = 0; i$ < len$; i$++) {
			String str = arr$[i$];
			perfplanDAO.exeHql((new StringBuilder()).append(
					"update Perfplan pp set pp.ppStatus = ").append(status)
					.append(" where pp.ppId = '").append(str).append("'")
					.toString());
		}

	}

	public boolean setPerfplanByPay(String yearMonth, Empsalarypay payArray[]) {
		if (ObjectUtils.isEmpty(payArray))
			return false;
		List empList = new ArrayList();
		Empsalarypay arr[] = payArray;
		int len = arr.length;
		for (int i = 0; i < len; i++) {
			Empsalarypay pay = arr[i];
			empList.add(pay.getEspEmpno());
		}

		Map perfplanMap = getPerfplanMapByEmp(yearMonth, empList);
		if (perfplanMap == null)
			return false;
		arr = payArray;
		len = arr.length;
		for (int i = 0; i < len; i++) {
			Empsalarypay pay = arr[i];
			pay.setPerfplans((List) perfplanMap.get(pay.getEspEmpno().getId()));
		}

		return true;
	}

	public List searchByDepts(String depts, String psId, String pppId) {
		DetachedCriteria dc = DetachedCriteria.forClass(Perfplan.class);
		dc.createAlias(Perfplan.PROP_PP_PS_ID, "ppPsId", 1);
		dc.createAlias(Perfplan.PROP_PP_PPP_ID, "ppPppId", 1);
		dc.createAlias(Perfplan.PROP_PP_EMP_ID, "ppEmpId", 1);
		BaseCrit.addDC(dc, (new StringBuilder()).append(Perfplan.PROP_PP_PS_ID)
				.append(".").append(Perfschema.PROP_PS_ID).toString(), "eq",
				new String[] { psId });
		BaseCrit.addDC(dc, (new StringBuilder())
				.append(Perfplan.PROP_PP_PPP_ID).append(".").append(
						Perfplanperiod.PROP_PPP_ID).toString(), "eq",
				new String[] { pppId });
		String str[] = depts.split(",");
		IDepartmentBO departmentBo = (IDepartmentBO) BaseAction
				.getBean("departmentBO");
		String allSubDepts[] = null;
		if (!"rootid".equalsIgnoreCase(str[0]) && !"".equalsIgnoreCase(str[0]))
			allSubDepts = departmentBo.getAllSubDeptIds(1, str[0]);
		else
			allSubDepts = departmentBo.getAllSubDeptIds(1, "rootid");
		BaseCrit.addDC(dc, (new StringBuilder()).append("ppEmpId.").append(
				Employee.PROP_EMP_DEPT_NO).append(".id").toString(), "in",
				allSubDepts);
		return perfplanDAO.findByCriteria(dc);
	}

	public Map getPerfplanMapByEmp(String yearMonth, List empList) {
		if (empList == null || empList.size() == 0)
			return null;
		DetachedCriteria dc = DetachedCriteria.forClass(Perfplan.class);
		dc.createAlias(Perfplan.PROP_PP_EMP_ID, "ppEmpId", 1);
		dc.createAlias(Perfplan.PROP_PP_PPP_ID, "ppPppId", 1);
		dc.add(Restrictions.eq(Perfplan.PROP_PP_STATUS, Integer.valueOf(3)));
		dc.add(Restrictions.eq((new StringBuilder()).append("ppPppId.").append(
				Perfplanperiod.PROP_PPP_YEARMONTH).toString(), yearMonth));
		if (empList.size() < 500) {
			Set empIds = new HashSet();
			Employee emp;
			for (Iterator i$ = empList.iterator(); i$.hasNext(); empIds.add(emp
					.getId()))
				emp = (Employee) i$.next();

			dc.add(Restrictions.in((new StringBuilder()).append("ppEmpId.")
					.append(Employee.PROP_ID).toString(), empIds));
		}
		List perfplanList = perfplanDAO.findByCriteria(dc);
		if (perfplanList.isEmpty())
			return null;
		Set ppIds = new HashSet();
		Iterator i$ = perfplanList.iterator();
		do {
			if (!i$.hasNext())
				break;
			Perfplan pp = (Perfplan) i$.next();
			if ("1".equals(pp.getPpPppId().getPppClass()))
				ppIds.add(pp.getPpId());
		} while (true);
		if (!ppIds.isEmpty()) {
			DetachedCriteria dcPps = DetachedCriteria
					.forClass(Perfplanscore.class);
			dcPps.add(Restrictions.in((new StringBuilder()).append(
					Perfplanscore.PROP_PPS_PP_ID).append(".").append(
					Perfplan.PROP_PP_ID).toString(), ppIds));
			dcPps.addOrder(Order.asc(Perfplanscore.PROP_PPS_DATA_SEQ));
			List planScoreList = perfplanDAO.findByCriteria(dcPps);
			Iterator iter = planScoreList.iterator();
			for (Iterator it = perfplanList.iterator(); it.hasNext();) {
				Perfplan pp = (Perfplan) it.next();
				while (iter.hasNext()) {
					Perfplanscore pps = (Perfplanscore) iter.next();
					if (pp.getPpId().equals(pps.getPpsPpId().getPpId())) {
						if (pp.getPlanScoreList() == null)
							pp.setPlanScoreList(new LinkedList());
						pp.getPlanScoreList().add(pps);
						iter.remove();
					}
				}
			}

		}
		Map result = new HashMap();
		Perfplan pp;
		for (Iterator it = perfplanList.iterator(); it.hasNext(); ((List) result
				.get(pp.getPpEmpId().getId())).add(pp)) {
			pp = (Perfplan) it.next();
			if (!result.containsKey(pp.getPpEmpId().getId()))
				result.put(pp.getPpEmpId().getId(), new ArrayList());
		}

		return result;
	}

	public Map searchAllPlanNames() {
		String hql = "select perf.ppNo ,perf.ppId from Perfplan perf";
		List tempList = perfplanDAO.exeHqlList(hql);
		Map resultMap = new HashMap();
		Object p[];
		for (Iterator i$ = tempList.iterator(); i$.hasNext(); resultMap.put(
				p[0].toString(), p[1].toString()))
			p = (Object[]) i$.next();

		return resultMap;
	}

	private IPerfplanDAO perfplanDAO;
}
